package cn.tedu.sims.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.net.*;
import java.util.Enumeration;
import java.util.List;

@Slf4j
public class QueryIpUtil {
    /**
     * 获取真实IP
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        // 判断是否为反向代理,多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
        // 是取X-Forwarded-For中第一个非unknown的有效IP字符串
        if (ip != null && !"".equals(ip) && !"unknown".equalsIgnoreCase(ip)) {
            String[] tempArray = ip.split(",");
            for (String val : tempArray) {
                if (!"unknown".equalsIgnoreCase(val)) {
                    ip = val.replaceAll("\\s", "");
                    break;
                }

            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-forvarded-for");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("x-real-ip");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            try {
                ip = request.getRemoteAddr();
            } catch (Exception e) {
                log.warn(e.getMessage(), e);
                ip = "unknown";
            }
        }
        return ip;
    }
    /**
     * 获取本机地址
     */
    public static String getLocalIp() {
        String ip = null;
        try {
            Enumeration<?> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();
                for (InterfaceAddress add : InterfaceAddress) {
                    InetAddress Ip = add.getAddress();
                    if (Ip != null && Ip instanceof Inet4Address) {
                        ip = Ip.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            log.warn(e.getMessage(), e);
        }
        return ip;
    }


}
